package com.quzhi.sys.controller.receiveGoods;

import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quzhi.common.Result;
import com.quzhi.common.Utils;
import com.quzhi.common.code.Code;
import com.quzhi.sys.dto.ReceiveGoodsDto;
import com.quzhi.sys.entity.GoodsSerialNumber;
import com.quzhi.sys.entity.OrderSerialNumber;
import com.quzhi.sys.entity.ReceiveGoods;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.service.impl.GoodsSerialNumberServiceImpl;
import com.quzhi.sys.service.impl.OrderSerialNumberServiceImpl;
import com.quzhi.sys.service.impl.ReceiveGoodsServiceImpl;
import com.quzhi.sys.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Xibing
 * @since 2024-07-09
 */
@RestController
@RequestMapping("/sys/receiveGoods")
@Slf4j
public class ReceiveGoodsController {

    @Autowired
    private ReceiveGoodsServiceImpl goodsService;


    @Autowired
    private GoodsSerialNumberServiceImpl goodsSerialNumberService;

    @Autowired
    private UserServiceImpl userService;


    // 添加收货记录
    @PostMapping
    public Result<?> addGoods(@RequestBody ReceiveGoods receiveGoods, HttpServletRequest request) {


        // 获取录入用户
        String token = Utils.getToken(request);
        User userinfoForBack = userService.getUserinfoForBack(token);

        // 初始化
        receiveGoods.setId(UUID.randomUUID().toString());
        receiveGoods.setCreateTime(LocalDateTime.now());
        receiveGoods.setUpdateTime(LocalDateTime.now());


        // 分割序列号
        StringBuilder message = new StringBuilder();
        String serialNumbers = receiveGoods.getSerialNumber();
        if (serialNumbers != null) {
            String[] serialNumber = serialNumbers.split("/");

            for (String s : serialNumber) {
                // 添加序列号
                message.append(goodsSerialNumberService.addGoodsSerialNumber(s, receiveGoods.getId()));
            }

        }

        if (!message.toString().equals("")) return Result.fail(Code.UPDATE_FAIL_CODE, message.toString());

        receiveGoods.setOperator(userinfoForBack.getUsername());

        goodsService.save(receiveGoods);

        return Result.success("添加成功," + message);
    }


    @GetMapping("/list")
    public Result<?> getGoodsList(@RequestParam(value = "oddNumber", required = false) String oddNumber,
                                  @RequestParam(value = "serialNumber", required = false) String serialNumber,
                                  @RequestParam(value = "type", required = false) String type,
                                  @RequestParam(value = "createTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime,
                                  @RequestParam(value = "pageNo") Long pageNo,
                                  @RequestParam(value = "pageSize") Long pageSize) {


        List<Map<String, Object>> rows = new ArrayList<>();
        if (serialNumber != null && !serialNumber.equals("")) {

            // 更具序列号查询
            LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GoodsSerialNumber::getSerialNumber, serialNumber);
            List<GoodsSerialNumber> list = goodsSerialNumberService.list(wrapper);

            List<ReceiveGoodsDto> needGoodsRecordDtoList = goodsService.getNeedGoodsRecordDtoList(list);

            List<ReceiveGoodsDto> paginate = Utils.paginate(needGoodsRecordDtoList, pageNo, pageSize);

            // 只添加满处序列号的订单
            for (ReceiveGoods record : paginate) {
                Map<String, Object> row = new HashMap<>();
                row.put("id", record.getId());
                row.put("info", Utils.goodsInfo(record.getInfo()));
                row.put("oddNumber", record.getOddNumber());
                row.put("remark", record.getRemark());
                row.put("serialNumbers", list); // 返回序列号集合
                row.put("operator", record.getOperator());
                row.put("type", record.getType()); // 返回序列号集合
                row.put("createTime", record.getCreateTime());
                rows.add(row);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("rows", rows);
            data.put("total", needGoodsRecordDtoList.size());

            return Result.success(data);
        } else {
            // 定义模糊查询条件
            LambdaQueryWrapper<ReceiveGoods> wrapper = new LambdaQueryWrapper<>();

            if (createTime != null) {
                LocalDateTime min = LocalDateTime.of(createTime.getYear(), createTime.getMonth(), createTime.getDayOfMonth(), 0, 0, 0);
                LocalDateTime max = LocalDateTime.of(createTime.getYear(), createTime.getMonth(), createTime.getDayOfMonth() + Code.ONE, 0, 0, 0);
                // 查询 指定日期的订单
                wrapper.ge(ReceiveGoods::getCreateTime, min); // eq等于
                wrapper.le(ReceiveGoods::getCreateTime, max); // eq等于
            }

            wrapper.eq(StringUtils.hasLength(oddNumber), ReceiveGoods::getOddNumber, oddNumber);
            wrapper.eq(StringUtils.hasLength(type), ReceiveGoods::getType, type);

            // 根据创建时间排序
            wrapper.orderByDesc(ReceiveGoods::getCreateTime);

            //  分页查询数据
            Page<ReceiveGoods> receiveGoodsPage = new Page<>(pageNo, pageSize);

            goodsService.page(receiveGoodsPage, wrapper);

            List<ReceiveGoods> records = receiveGoodsPage.getRecords();


            for (ReceiveGoods record : records) {

                // 获取序列号集合
                // 查询序列号集合(收货)
                LambdaQueryWrapper<GoodsSerialNumber> goodsSerialNumberLambdaQueryWrapper = new LambdaQueryWrapper<>();
                goodsSerialNumberLambdaQueryWrapper.eq(GoodsSerialNumber::getReceiveGoodsId, record.getId());

                Map<String, Object> row = new HashMap<>();


                List<GoodsSerialNumber> list = goodsSerialNumberService.list(goodsSerialNumberLambdaQueryWrapper);


                row.put("id", record.getId());
                row.put("info", Utils.goodsInfo(record.getInfo()));
                row.put("oddNumber", record.getOddNumber());
                row.put("remark", record.getRemark());
                row.put("serialNumbers", list); // 返回序列号集合
                row.put("operator", record.getOperator());
                row.put("type", record.getType()); // 返回序列号集合
                row.put("createTime", record.getCreateTime());


                rows.add(row);
            }


            Map<String, Object> data = new HashMap<>();

            data.put("rows", rows);
            data.put("total", receiveGoodsPage.getTotal());
            return Result.success(data);
        }

    }

    @GetMapping("/{id}")
    public Result<?> getGoodsById(@PathVariable("id") String id) {
        ReceiveGoods record = goodsService.getById(id);

        Map<String, Object> row = new HashMap<>();


        LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GoodsSerialNumber::getReceiveGoodsId, id);
        List<GoodsSerialNumber> list = goodsSerialNumberService.list(wrapper);
//        添加序列号待完善

        StringBuilder serialNumber = new StringBuilder();

        for (GoodsSerialNumber goodsSerialNumber : list) {
            serialNumber.append(goodsSerialNumber.getSerialNumber()).append("/");
        }


        String s = Utils.removeLastSlash(serialNumber.toString());

        row.put("id", record.getId());
        row.put("info", Utils.goodsInfo(record.getInfo()));
        row.put("oddNumber", record.getOddNumber());
        row.put("remark", record.getRemark());
        row.put("serialNumber", s);
        row.put("type", record.getType());
        row.put("createTime", record.getCreateTime());

        return Result.success(row);
    }


    @PutMapping
    public Result<?> updateById(@RequestBody Map<String, Object> receiveGoods) {

        try {
            String id = (String) receiveGoods.get("id");
            String info = (String) receiveGoods.get("info");
            String oddNumber = (String) receiveGoods.get("oddNumber");
            String remark = (String) receiveGoods.get("remark");
            String serialNumbers = (String) receiveGoods.get("serialNumber");
            LocalDateTime createTime = Utils.convertToLocalDateTimeToDate((String) receiveGoods.get("createTime"));


            // 序列号更具/分割先删除原有库中的序列号，再添加
            String[] serialNumber = serialNumbers.split("/");

            // 删除订单绑定的所有序列号
            LambdaQueryWrapper<GoodsSerialNumber> goodsSerialNumberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            goodsSerialNumberLambdaQueryWrapper.eq(GoodsSerialNumber::getReceiveGoodsId, id);
            goodsSerialNumberService.remove(goodsSerialNumberLambdaQueryWrapper);

            //
            StringBuilder message = new StringBuilder();

            // 重新添加
            for (String s : serialNumber) {
                String s1 = goodsSerialNumberService.addGoodsSerialNumber(s, id);
                message.append(s1);
            }

            if (!message.toString().equals("")) return Result.fail(Code.UPDATE_FAIL_CODE, message.toString());


            ReceiveGoods goods = new ReceiveGoods();
            goods.setId(id);
            goods.setOddNumber(oddNumber);
            goods.setRemark(remark);
            goods.setSerialNumber(serialNumbers);
            goods.setCreateTime(createTime);

            goods.setInfo(info);

            goodsService.updateById(goods);

            return Result.success("更新成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail(Code.UPDATE_FAIL_CODE, "更新失败");
        }

    }


    @DeleteMapping("/{id}")
    public Result<?> deletedById(@PathVariable("id") String id) {

        goodsService.removeById(id);

        // 删除绑定的序列号
        LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GoodsSerialNumber::getReceiveGoodsId, id);
        goodsSerialNumberService.remove(wrapper);

        return Result.success("删除成功");
    }


}
